﻿using System.ComponentModel.DataAnnotations.Schema;
using System.Reflection;
using System.Text.Json.Serialization;

namespace XYAC.Framework.WohuaMesExtend.IHI.Extensions
{
    public static class ObjectComparer
    {
        public static List<string> CompareInstances<T>(this T obj1, T obj2)
        {
            List<string> differences = new List<string>();

            if (obj1 == null || obj2 == null)
            {
                throw new ArgumentNullException("Both objects must be non-null.");
            }

            Type type = typeof(T);
            PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo property in properties)
            {
                object value1 = property.GetValue(obj1, null);
                object value2 = property.GetValue(obj2, null);

                // 检查是否有 NotMapped 或 JsonIgnore 属性
                var notMappedAttr = (NotMappedAttribute)Attribute.GetCustomAttribute(property, typeof(System.ComponentModel.DataAnnotations.Schema.NotMappedAttribute));
                var jsonIgnoreAttr = (JsonIgnoreAttribute)Attribute.GetCustomAttribute(property, typeof(JsonIgnoreAttribute));

                if (notMappedAttr != null || jsonIgnoreAttr != null)
                {
                    // 如果存在，跳过这个属性
                    continue;
                }
                // 比较 null 值情况
                if (value1 == null && value2 != null || value1 != null && value2 == null)
                {
                    differences.Add($"{property.Name}: {value1 ?? "null"} != {value2 ?? "null"}");
                }
                else if (value1 != null && !value1.Equals(value2))
                {
                    differences.Add($"{property.Name}: {value1} != {value2}");
                }
            }

            return differences;
        }
    }

}
